package view.post

import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.updateLayoutParams
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder
import com.starblink.android.basic.appsflyer.AppsflyerManager
import com.starblink.basic.apollo.ext.ApolloValSetExt
import com.starblink.android.basic.ext.click
import com.starblink.android.basic.ext.inflater
import com.starblink.android.basic.modules.mine.MineManager
import com.starblink.android.basic.sensorsdata.extension.trackData
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.impl.SpmTrackHandler
import com.starblink.android.basic.user.LoginCheckInterceptor
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.util.ImageUtils
import com.starblink.android.basic.util.post.CommonMutateManage
import com.starblink.android.common.R
import com.starblink.android.common.databinding.ItemPostCardBinding
import com.starblink.basic.log.SKLogger
import com.starblink.basic.util.CommUtils
import com.starblink.library.widget.product.ProductCardView
import com.starblink.rocketreserver.fragment.PostF
import com.starblink.videocache.cache.PreloadManager

class PostCardView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleRes: Int = 0,
) : ConstraintLayout(context, attrs, defStyleRes) {
    lateinit var post: PostF

    var gsyVideoOptionBuilder: GSYVideoOptionBuilder? = null
    val binding: ItemPostCardBinding = ItemPostCardBinding.inflate(inflater, this, true)

    var pos = 0

    companion object {
        const val TAG = "PostCardView"
    }


    fun bindPost(
        post: PostF,
        position: Int,
        playAuto: Boolean = false, spmPageValue: Int,
        listener: () -> Unit,
    ) {
        this.post = post
        this.pos = position

        trackData(
            element = SpmElementDef.PostCard,
            page = spmPageValue,
            traceInfo = post.traceInfo,
            params = SpmTrackHandler.trackPostMap(
                position,
                post
            )
        )
        setLayoutSize(post, binding)

        binding.tvName.text = post.posterInfo.poster.username ?: ""
        ImageUtils.loadImage(
            context, post.posterInfo.poster.headImage ?: "", binding.ivUser,
            com.starblink.basic.style.R.mipmap.mine_default_avatar,
            com.starblink.basic.style.R.mipmap.mine_default_avatar
        )

        if (post.content != null && post.content != "") {
            binding.tvTitle.visibility = View.VISIBLE
            binding.tvTitle.text = post.content ?: ""
        } else {
            binding.tvTitle.visibility = View.GONE
        }

        binding.tvLikeNum.text = post.likeNumbers.toString()
        if (post.liked) {
            binding.ivLike.setImageResource(com.starblink.basic.style.R.mipmap.video_like)
        } else {
            binding.ivLike.setImageResource(
                com.starblink.basic.style.R.mipmap.unlike
            )
        }
        binding.ivLike.click {//点赞
            if (context != null && binding.tvLikeNum.text == post.likeNumbers.toString()) {
                CommonMutateManage.likePost(
                    context,
                    post.id,
                    post.contentType,
                    post.posterInfo.poster.id,
                    post.liked,
                    post.likeNumbers,
                    {
                        changeLikeState(
                            !post.liked,
                            if (!post.liked) post.likeNumbers + 1 else post.likeNumbers - 1
                        )
                    }) { like, count ->
                    ApolloValSetExt.setApolloVal<PostF>(post, "liked", like)
                    ApolloValSetExt.setApolloVal<PostF>(post, "likeNumbers", count)

                    changeLikeState(like, count)
                }
            }
        }

        binding.tvName.click {//跳转个人中心
            toAccount(post)
        }
        binding.ivUser.click {//跳转个人中心
            toAccount(post)
        }
        binding.ivPost.skTrackTag(listener, spmPageValue, post)

        binding.tvTitle.skTrackTag(listener, spmPageValue, post)

        if (post.contentType == "2") {//视频
            binding.ivType.setImageResource(R.mipmap.video_flag)
            binding.ivType.visibility = View.VISIBLE
            if (playAuto) {
                binding.ivPost.visibility = View.GONE
                binding.videoPlayer.visibility = View.VISIBLE
                binding.videoPlayer.skTrackTag(listener, spmPageValue, post)

                binding.prepareView.setThumbImg(context, post.mainPic)
            }

            val pictures = post.pictures
            if (pictures != null && pictures.isNotEmpty()) {
                val picUrl = pictures[0].pictureF.picUrl
                PreloadManager.getInstance(context).addPreloadTask(picUrl, position)
            }
        } else {//图文
            binding.ivPost.visibility = View.VISIBLE
            binding.videoPlayer.visibility = View.GONE
            val picSize: Int? = post.pictures?.size
            if (picSize != null) {
                if (picSize > 1) {
                    binding.ivType.setImageResource(R.mipmap.icon_main_img)
                    binding.ivType.visibility = View.VISIBLE
                } else {
                    binding.ivType.visibility = View.GONE
                }
            }
        }
        if (post.posterInfo.poster.deleted == true) {
            binding.tvName.text = "Account Deleted"
            binding.tvName.setTextColor(CommUtils.getColor(com.starblink.basic.style.R.color.sk_gray400))
        } else {
            binding.tvName.setTextColor(CommUtils.getColor(com.starblink.basic.style.R.color.sk_gray800))
        }
    }

    private fun View.skTrackTag(listener: () -> Unit, spmPageValue: Int, post: PostF) {
        trackData(
            element = SpmElementDef.PostCard,
            page = spmPageValue,
            onlyHit = true,
            traceInfo = post.traceInfo,
            params = SpmTrackHandler.trackPostMap(pos, post)
        )
        click {
            AppsflyerManager.reportContentClick(
                mapOf(
                    "af_content_id" to post.id,
                    "af_content_type" to (post.contentType ?: "1"),
                )
            )
            listener.invoke()
        }
    }

    private fun toAccount(post: PostF) {
        LoginCheckInterceptor.check2Login(context) {
            if (UserDataCenter.getAccountInfo()?.id == post.posterInfo.poster.id) {
                MineManager.navigationToMinePersonHome(context)
            } else {
                MineManager.navigationToOtherUserPersonHome(
                    context,
                    accountId = post.posterInfo.poster.id,
                    accountDeleted = post.posterInfo.poster.deleted,
                    userName = post.posterInfo.poster.username
                )
            }
        }
    }

    private fun changeLikeState(liked: Boolean = false, likeNum: Int) {
        if (liked) {
            binding.ivLike.setImageResource(com.starblink.basic.style.R.mipmap.video_like)
        } else {
            binding.ivLike.setImageResource(
                com.starblink.basic.style.R.mipmap.unlike
            )
        }
        binding.tvLikeNum.text = "$likeNum"
    }

    private fun setLayoutSize(post: PostF, binding: ItemPostCardBinding) {
        binding.cvTop.run {
            updateLayoutParams<ConstraintLayout.LayoutParams> {
                this.dimensionRatio =
                    if (post.mainPicSize.isNullOrEmpty()) "1" else post.mainPicSize?.let {
                        var ratio = 1f
                        try {
                            ratio = it.split("*").let { list ->
                                list[0].toFloat() / list[1].toFloat()
                            }
                        } catch (e: Exception) {
                            SKLogger.e(ProductCardView.TAG, e.message ?: "mainPicSize parse erro")
                        }
                        ratio.toString()
                    }
            }
            ImageUtils.loadImage(
                context,
                post.mainPic,
                binding.ivPost
            )
        }
    }

}